﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using WebNext.Domain.Entities;
using NHibernate.SqlTypes;
using System.Data;
using System.Xml.Serialization;
using System.IO;
using NHibernate;

namespace WebNext.DataAccess.Mappings
{
	class EntryContentXmlSerializer : IUserType
	{
		private XmlSerializer serializer;
		
		public EntryContentXmlSerializer()
		{
			this.serializer = new XmlSerializer(typeof(List<EntryElement>));
		}

		public object Assemble(object cached, object owner)
		{
			return cached;
		}

		public object DeepCopy(object value)
		{
			return value;
		}

		public object Disassemble(object value)
		{
			return value;
		}

		public bool Equals(object x, object y)
		{
			return object.Equals(x, y);
		}

		public int GetHashCode(object x)
		{
			return x.GetHashCode();
		}

		public bool IsMutable
		{
			get { return false; }
		}

		public object NullSafeGet(System.Data.IDataReader rs, string[] names, object owner)
		{
			string contentString = NHibernateUtil.AnsiString.NullSafeGet(rs, names[0]) as string;
			if (string.IsNullOrEmpty(contentString))
			{
				return null;
			}
			else
			{
				using (TextReader textReader = new StringReader(contentString))
				{
					return this.serializer.Deserialize(textReader);
				}
			}
		}

		public void NullSafeSet(System.Data.IDbCommand cmd, object value, int index)
		{
			IDataParameter parameter = (IDataParameter)cmd.Parameters[index];
			if (value ==null)
			{
				parameter.Value = DBNull.Value;
			}
			else
			{
				using (TextWriter textWriter = new StringWriter())
				{
					serializer.Serialize(textWriter, value);
					parameter.Value = textWriter.ToString();
				}
			}
		}

		public object Replace(object original, object target, object owner)
		{
			return original;
		}

		public Type ReturnedType
		{
			get { return typeof(Entry); }
		}

		public NHibernate.SqlTypes.SqlType[] SqlTypes
		{
			get { return new SqlType[] { new StringSqlType() }; }
		}
	}
}
